/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package control;

import dao.UserDao;
import entity.User;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import javax.xml.ws.WebServiceRef;

/**
 *
 * @author AnBoCa
 */
@ManagedBean(name="userLogin")
@RequestScoped
public class UserLogin {
    @WebServiceRef(wsdlLocation = "WEB-INF/wsdl/localhost_8080/UserActions/UserActions.wsdl")
    private UserActions_Service service;

    private String user;
    private String pass;
    
    public UserLogin() {
    }

    public String getPass() {
        return pass;
    }

    public void setPass(String pass) {
        this.pass = pass;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }
    
    public String doUserLogin(){
        
//condicion para probar el login sin la bd
        if (this.user.trim().equals("compujuy")){
            //manda al index
            return "login";
        }
        //ingresar consulta a el web service
        boolean res=doLogin(user,pass);
        if (res){
            //redireccionar y demas
            UserDao userDao=new UserDao();
            User userS=userDao.findUsuarioByUserName(user);
            HttpSession session= (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
            session.setAttribute("user", userS);
            FacesContext fc=FacesContext.getCurrentInstance();
            try {
                fc.getExternalContext().redirect(fc.getExternalContext().getRequestContextPath()+"/index.xhtml");
            } catch (IOException ex) {
                Logger.getLogger(UserLogin.class.getName()).log(Level.SEVERE, null, ex);
            }
        }else{
            //enviar un mensaje de confirmacion
            FacesContext.getCurrentInstance().addMessage("loginGrid:user", new FacesMessage(FacesMessage.SEVERITY_ERROR,"","no se pudo iniciar la session"));
            
        }
        //en caso de no encontrar la opcion retorna errorlogin el cual regresa a la pag anterior
        return "ErrorLogin";
    }

    private boolean doLogin(java.lang.String user, java.lang.String pass) {
        control.UserActions port = service.getUserActionsPort();
        return port.doLogin(user, pass);
    }
    
}
